//
//  PushForSearch.m
//  HYHoney
//
//  Created by dllo on 16/2/26.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "PushForSearch.h"
#import "SearchOfCell.h"
#import "NetworkingHandle.h"
#import "ModelForSearch.h"
#import "PushPush.h"
#import "DKNightVersion.h"

@interface PushForSearch ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UIView *viewForNail;
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) UISearchBar *search;
@property (nonatomic, retain) NSString *url;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) UITableView *tableView;

@end

@implementation PushForSearch

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self createtableView];
    
}

- (void)dealloc{

    [_viewForNail release];
    [_button release];
    [_search release];
    [_url release];
    [_array release];
    [_tableView release];
    [super dealloc];
}


-(void)createtableView{
    
    // 创建搜索栏
    self.search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 4 * 3, self.view.frame.size.height / 15)];
    
    [self.view addSubview:self.search];
    self.search.placeholder = @"输入需要搜索的内容";
    self.search.dk_backgroundColorPicker = DKColorWithColors([UIColor lightGrayColor], [UIColor blueColor]);
    [self.search release];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 15, self.view.frame.size.width, self.view.frame.size.height - 113 - self.view.frame.size.height / 15) style:UITableViewStylePlain];
    
    [self.view addSubview:self.tableView];
    [self.tableView release];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.dk_backgroundColorPicker =  DKColorWithRGB(0xFFFAFA, 0x27408B);
    
    [self.tableView registerClass:[SearchOfCell class] forCellReuseIdentifier:@"pool"];
    
    self.tableView.userInteractionEnabled = YES;

    
    // 确定搜索按键
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    self.button.frame = CGRectMake(self.view.frame.size.width / 4 * 3, 0, self.view.frame.size.width / 4, self.view.frame.size.height / 15);
    [self.view addSubview:self.button];
    self.button.dk_backgroundColorPicker = DKColorWithColors([UIColor lightGrayColor], [UIColor lightGrayColor]);
    [self.button setTitle:@"确定" forState:UIControlStateNormal];
    
    [self.button addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 创建返回上一个界面的 button
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.button.frame = CGRectMake(5, 5, 30, 30);
    [self.navigationController.navigationBar addSubview:self.button];
    [self.button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    //    self.tableView.tableHeaderView = search;
    
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"ISNIGHT"]) {
        
        self.search.keyboardAppearance = UIKeyboardAppearanceDark;
        
    }else {
        
        self.search.keyboardAppearance = UIKeyboardAppearanceLight;
    }
    
    
}


-(void)searchAction:(UIButton *) button {
    
    // 如果有中文将搜索的内容进行转码
    
//        NSString *temp = [self.search.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSString *url =@"http://api.wsq.umeng.com/v2/feed/search?os=iOS&openudid=c4fef44ea2c33987b846791b59bd050a622bea9b&sdkv=2.2.1&ak=5636cff167e58ef91b0001ae&de=iPhone5,2&mac=02:00:00:00:00:00&uid=56cfc0c97019c90972c5ff64&keywords=";
    
    NSString *url2 = @"&topic_id=568b2560ee78505f3e9da44c&count=20";
    self.url = [url stringByAppendingFormat:@"%@%@", self.search.text, url2];
    
    NSLog(@"%@",self.url);
    [NetworkingHandle networkingWithURL:self.url completeHandel:^(NSURLResponse *response, NSData *data, id result) {
        
        self.array = [NSMutableArray array];
        
        NSArray *arr = [result objectForKey:@"items"];
        
        NSLog(@"%@",arr);
        for (NSDictionary *dic in arr) {
            
            NSLog(@"%@",dic);
            ModelForSearch *model = [[ModelForSearch alloc]init];
            
            [model setValuesForKeysWithDictionary:dic];
            model.content = [dic objectForKey:@"content"];
            model.share_link = [dic valueForKey:@"share_link"];
            
            [self.array addObject:model];
        }
        
        [self.tableView reloadData];
    }];
    
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.array.count;
}




// 空白处回收键盘
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.tableView endEditing:YES];
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SearchOfCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    
    ModelForSearch *model = [self.array objectAtIndex:indexPath.row];
    
    [cell passModel:model];
    
    // 带属性的字符串实现关键字高亮
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:model.content];
    
    [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[model.content rangeOfString:self.search.text]];
    [cell.content setAttributedText :attribute];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return self.view.frame.size.height / 8;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PushPush *search =[[PushPush alloc]init];
    
    ModelForSearch *model = [self.array objectAtIndex:indexPath.row ];
    [search passSecondModel:model];
    
    [self.navigationController pushViewController:search animated:YES];
    
}


- (void)buttonAction {
    
    [self.navigationController popViewControllerAnimated:YES];
    
    //当点击 button 的时候让顶部的 view 和 button 隐藏同时进入上一个 vc
    self.viewForNail.hidden = YES;
    self.button.hidden = YES;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
